using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Web.Services.Protocols;

namespace SPWebShell.cmdlet
{
    ///
    /// Deletes the specified list item from SharePoint
    ///

    [Cmdlet(VerbsCommon.Remove, "SPListItem")]
    public class DeleteSPListItemsCmdLet : CmdLetBase
    {

        public DeleteSPListItemsCmdLet()
        {
        }
        [Parameter(Mandatory = true, HelpMessage = "The title of the List")]
        [Alias("listname", "name")]
        [ValidateNotNullOrEmpty]
        public string List { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The absolute URL to the web site where the List is located or any item/view within the List. e.g. http://server/sites/SiteA/doclib1/Allitems.aspx")]
        [ValidateNotNullOrEmpty]
        public string Url { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The ID of the list item to be deleted")]
        [Alias("SPID")]
        [ValidatePattern("[0-9]{1,}")]
        public Int32 ID { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                VerboseLogger("Start time: " + DateTime.Now.ToString());
                ISPRepository repos = base.SPRepos;
                SPDoclibLocation location = repos.ResolveDoclibUrlFromPageUrl(this.Url);
                //If a List name has been provided then use this name
                if (!string.IsNullOrEmpty(this.List)) location.DoclibName = this.List;
                //entity.SPList listInfo = this.GetListInfo(location);
                VerboseLogger("Deleting list item with ID:" + this.ID);
                repos.DeleteItem(location, this.ID);
                VerboseLogger("End time: " + DateTime.Now.ToString());
                VerboseLogger("Deleting completed");
                base.ProcessRecord();
            }
            catch (SoapException ex)
            {
                string message = ex.Detail.OuterXml;
                throw new Exception(message, ex);
            }
            finally
            {
                WriteVerbose("End time: " + DateTime.Now.ToString());
            }

        }
        entity.SPList GetListInfo(SPDoclibLocation listlocation)
        {
            this.VerboseLogger("Fetching metadata for the list:" + listlocation.DoclibName);
            entity.SPList listInfo = null;
            listInfo = base.SPRepos.GetList(listlocation);
            this.VerboseLogger("Metadata obtained:");
            return listInfo;
        }
    }
}
